import type { Plugin } from "vite";
import type { AddressInfo } from "net";
import { spawn } from "child_process";
import fs from "node:fs";
const buildBackground = () => {
  require("esbuild").buildSync({
    entryPoints: ["src/background.ts"],
    bundle: true,
    outfile: "dist/background.js",
    platform: "node",
    target: "node12",
    external: ["electron"],
  });
};
export const ElectronDevPlugin = (): Plugin => {
  return {
    name: "electron-dev",
    configureServer(server) {
      buildBackground();
      return () => {
        server?.httpServer?.on("listening", () => {
          const addressInfo = server.httpServer?.address() as AddressInfo;
          // spawn(require('electron'),[])
          const IP = `http://localhost:${addressInfo.port}`;
          let ElectronProcess = spawn(require("electron"), [
            "dist/background.js",
            IP,
          ]);
          fs.watchFile("src/background.ts", () => {
            ElectronProcess.kill();
            buildBackground();
            ElectronProcess = spawn(require("electron"), [
              "dist/background.js",
              IP,
            ]);
          });
          ElectronProcess.stderr.on('data',(data)=>{
            console.log('日志',data.toString())
          })
        });
      };
    },
  };
};
